package com.zhenyi.youqu.app;

import java.util.Date;

import com.cjw.model.DBMap;
import com.jfinal.aop.Clear;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.utils.AESUtils;
import com.utils.AuthUtils;
import com.youqu.common.model.YqShopUser;
import com.zhenyi.youqu.core.YQAppController;

/**
 * 商户接口
 * 
 * @author cen
 *
 */
public class ShopUserController extends YQAppController {

	private final String AES_KEY = "cdtousyk2kftsryq";

	private YqShopUser getShopUser() {
		// String uid = AuthUtils.getTokenUid(this);
		// YqShopUser shopUser = YqShopUser.dao.findById(uid);
		YqShopUser shopUser = YqShopUser.dao.findById(23);
		return shopUser;
	}

	/**
	 * 登录
	 */
	@Clear
	public void auth() {
		String account = getPara("account");
		String password = getPara("password");
		if (!StrKit.notBlank(password, account)) {
			LogKit.info("账号/密码空");
			renderFailure("账号/密码错误");
			return;
		}
		try {
			password = AESUtils.decrypt(AES_KEY, password);
		} catch (Exception e) {
			LogKit.info("解密错误");
			renderFailure("账号/密码错误.");
			return;
		}
		if (password == null) {
			LogKit.info("解密失败");
			renderFailure("账号/密码错误.");
			return;
		}
		DBMap map = new DBMap();
		map.put("account", account);
		map.put("password", password);
		YqShopUser user = YqShopUser.dao.searchFirst(map);
		if (user == null) {
			LogKit.info("用户不存在");
			renderFailure(500, "账号/密码错误");
			return;
		}
		if (user.getStatus().equals(0)) {
			renderFailure(500, "账号已被禁用");
			return;
		}
		if (!user.getIsDeliver().equals(1)) {
			LogKit.info("不是派送员");
			renderFailure(500, "账号已被禁用.");
			return;
		}
		user.setLoginTime(new Date());
		user.update();
		String token = AuthUtils.login(String.valueOf(user.getId()));
		DBMap userInfo = new DBMap();
		userInfo.put("token", token);
		userInfo.put("name", user.getName());
		userInfo.put("mobile", user.getMobile());
		userInfo.put("location", user.getLocation());
		renderSuccess(userInfo);
	}

	/**
	 * 更新位置
	 */
	// @Before(SignInterceptor.class)
	public void updateLocation() {
		String location = getPara("location");
		YqShopUser shopUser = getShopUser();
		if (StrKit.isBlank(location)) {
			renderFailure("no location");
			return;
		}
		if (location.split(",").length != 2) {
			renderFailure("location error");
			return;
		}
		shopUser.setLocation(location);
		shopUser.update();
		renderSuccess();
	}

	/**
	 * 我的订单
	 */
	public void order() {
	}

	/**
	 * 订单详情
	 */
	public void orderInfo() {
	}
}
